package HDFSTest;

import org.simgrid.msg.Host;
import org.simgrid.msg.HostFailureException;
import org.simgrid.msg.Msg;
import org.simgrid.msg.MsgException;
import org.simgrid.msg.Process;
import org.simgrid.msg.Task;
import org.simgrid.msg.TimeoutException;
import org.simgrid.msg.TransferFailureException;

public class HDFS extends Process {
	private int numNamed;

	public HDFS(Host host, String name, String[] args) {
		super(host, name, args);
	}

	@Override
	public void main(String[] args) throws MsgException {
		Msg.info("HDFS start");
		numNamed = Integer.parseInt(args[0]);// checking the number of name nodes
		Task received = Task.receive(this.getClass().getName(), 0.5);// wait to receive task
		while (received != null) {// loop while still getting requests
			if (received instanceof FileRequest) {
				handleFileRequest((FileRequest) received);
				// wait for actually makes time pass for the process. Seems like a quantized appraoch of this+receiveTask
				// is the way to go.
				this.waitFor(0.1);
			}
			try {
				received = Task.receive(this.getClass().getName(), 0.5);
			} catch (TimeoutException e) {
				received = null;
			}
		}
	}

	public boolean handleFileRequest(FileRequest event) throws TransferFailureException, HostFailureException,
			org.simgrid.msg.TimeoutException {
		Msg.info("Handling file request " + event.getFileName() + " for " + event.isWrite());

		if (event.isWrite()) {

		} else
			for (int i = 1; i <= numNamed; i++) {
				String name = "nameNode" + i;
				event.send(name);
				try {
					event = (FileRequest) Task.receive(this.getClass().getName(), 0.5);
				} catch (NullPointerException e) {
					e.printStackTrace();
				}
				if (event.getResponse() != null) {
					Msg.info("Received file " + event.getFileName() + " sent by " + event.getName() + " from " + name);
					event.send(event.getName());
					return true;
				}

			}
		Msg.info("Name nodes not found for file " + event.getFileName());
		event.setComputeDuration((int) (Math.random() * 0.1));

		return false;
	}
}
